package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.MakeMoneyTable;
import com.web.exiaodao.business.entity.VSDCExperience;
import com.web.exiaodao.business.service.VSDCExperienceService;
import com.web.exiaodao.remote.service.ApiConfigurationTableService;
import com.web.exiaodao.remote.service.ApiMakeMoneyTableService;
import com.web.exiaodao.remote.vo.ConfigurationTableVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.repository.VSDCExperienceRepository;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.exiaodao.remote.vo.VSDCExperienceVo;

@Service("VSDCExperienceService")
@Transactional(readOnly = false)
public class VSDCExperienceServiceImpl extends BaseService<VSDCExperience> implements VSDCExperienceService {

    @Autowired
    private VSDCExperienceRepository VSDCExperienceRepository;

    @Autowired
    private ApiConfigurationTableService configurationTableService;


    @Autowired
    private ApiMakeMoneyTableService makeMoneyTableService;

    /**
     * 查询单条VSDCExperience信息
     * //@param tId
     *
     * @return 返回单个VSDCExperience对象
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<VSDCExperience> findOne(Long modelId) throws BusinessException {
        VSDCExperience obj = new VSDCExperience();
        if (modelId != 0) {
            obj = VSDCExperienceRepository.findByIdAndStatusNot(modelId, XaConstant.Status.delete);
        }
        XaResult<VSDCExperience> xr = new XaResult<VSDCExperience>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(obj);
        } else {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    /**
     * 分页查询状态非status的VSDCExperience数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象VSDCExperience集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<VSDCExperience>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<VSDCExperience> page = VSDCExperienceRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), VSDCExperience.class), pageable);
        XaResult<Page<VSDCExperience>> xr = new XaResult<Page<VSDCExperience>>();
        xr.setObject(page);
        return xr;
    }

    /**
     * 分页查询状态status的VSDCExperience数据
     *
     * @param status
     * @param filterParams
     * @param pageable
     * @return 返回对象VSDCExperience集合
     * @throws BusinessException
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public XaResult<Page<VSDCExperience>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<VSDCExperience> page = VSDCExperienceRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), VSDCExperience.class), pageable);
        XaResult<Page<VSDCExperience>> xr = new XaResult<Page<VSDCExperience>>();
        xr.setObject(page);
        return xr;
    }

    /**
     * 保存VSDCExperience信息
     *
     * @param model
     * @return
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<VSDCExperience> saveOrUpdate(VSDCExperience model) throws BusinessException {
        VSDCExperience obj = null;
        if (XaUtil.isNotEmpty(model.getId())) {
            obj = VSDCExperienceRepository.findOne(model.getId());
        } else {
            obj = new VSDCExperience();
        }
        obj.setJoniDate(model.getJoniDate());
        obj.setStatus(model.getStatus());
        obj.setVSDC_Id(model.getVSDC_Id());
        obj = VSDCExperienceRepository.save(obj);
        XaResult<VSDCExperience> xr = new XaResult<VSDCExperience>();
        xr.setObject(obj);
        return xr;
    }

    /**
     * 修改VSDCExperience状态，可一次修改多条   3删除  -1锁定  1正常
     * //@param userId
     *
     * @param modelIds
     * @param status
     * @return 返回VSDCExperience对象
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public XaResult<VSDCExperience> multiOperate(
            String modelIds, Integer status) throws BusinessException {
        XaResult<VSDCExperience> xr = new XaResult<VSDCExperience>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                VSDCExperience obj = VSDCExperienceRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = VSDCExperienceRepository.save(obj);
                } else {
                    throw new BusinessException(XaConstant.Message.object_not_find);
                }
            }
        }
        return xr;
    }

    /**
     * 分页查询，用户名，义工名查询
     */
    @Override
    public XaResult<Page<VSDCExperienceVo>> findVsdcList(Integer nextPage, Integer pageSize,
                                                         Map<String, Object> filterParams) throws BusinessException {
        //select v1.id, v1.vsdc_state, v1.joni_date,v2.vsdc_name,u.user_name,v1.`status`, v1.vsdc_id,v1.user_id from tb_xa_VSDCExperience v1
        //left join tb_xa_vsdc v2 on v2.id = v1.vsdc_id
        //left join tb_xa_user u on u.id = v1.user_id
        //where v1.`status`<>3
        StringBuffer sql = new StringBuffer("select  v1.id, v1.vsdc_state, v1.joni_date,v2.vsdc_name,u.user_name,u.`mobile`,v1.`status`, v1.vsdc_id,v1.user_id   ");
        sql.append("from tb_xa_VSDCExperience v1 ");
        sql.append("left join tb_xa_vsdc v2 on v2.id = v1.vsdc_id ");
        sql.append("left join tb_xa_user u on u.id = v1.user_id ");
        sql.append(" WHERE v1.STATUS<> ").append(XaConstant.Status.delete);
        //统计数据库中数据个数
        StringBuffer sql1 = new StringBuffer("select count(*) ");
        sql1.append("from tb_xa_VSDCExperience v1 ");
        sql1.append("left join tb_xa_vsdc v2 on v2.id = v1.vsdc_id ");
        sql1.append("left join tb_xa_user u on u.id = v1.user_id ");
        sql1.append(" WHERE v1.STATUS<> ").append(XaConstant.Status.delete);
        //查询条件
        //用户名
        if (XaUtil.isNotEmpty(filterParams.get("LIKE_userName"))) {
            sql.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
            sql1.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
        }
        //活动名称
        if (XaUtil.isNotEmpty(filterParams.get("LIKE_vSDC_Name"))) {
            sql.append(" AND v2.vsdc_name ").append(" like '%").append(filterParams.get("LIKE_vSDC_Name")).append("%' ");
            sql1.append(" AND v2.vsdc_name ").append(" like '%").append(filterParams.get("LIKE_vSDC_Name")).append("%' ");
        }
        //状态
        if (XaUtil.isNotEmpty(filterParams.get("EQ_vSDC_State"))) {
            sql.append(" AND v1.vsdc_state = '").append(filterParams.get("EQ_vSDC_State")).append("' ");
            sql1.append(" AND v1.vsdc_state = '").append(filterParams.get("EQ_vSDC_State")).append("' ");
        }
        if (XaUtil.isNotEmpty(filterParams.get("EQ_vSDCId"))) {
            sql.append(" AND v1.vsdc_id = '").append(filterParams.get("EQ_vSDCId")).append("' ");
            sql1.append(" AND v1.vsdc_id = '").append(filterParams.get("EQ_vSDCId")).append("' ");
        }
        sql.append(" ORDER BY v1.create_time DESC");
        sql1.append(" ORDER BY v1.create_time DESC");
        List<Object[]> objs = this.query(sql.toString(), nextPage * pageSize, pageSize);
        List<VSDCExperienceVo> vos = new ArrayList<VSDCExperienceVo>();
        for (Object[] obj : objs) {
            VSDCExperienceVo vo = new VSDCExperienceVo();
            UserVo uvo = new UserVo();
            vo.setId(Long.valueOf(obj[0].toString()));
            vo.setVSDC_State((XaUtil.isEmpty(obj[1]) ? 0 : Integer.valueOf(obj[1].toString())));
            vo.setJoniDate(XaUtil.isEmpty(obj[2]) ? "" : obj[2].toString());
            vo.setvSDC_Name(XaUtil.isEmpty(obj[3]) ? "" : obj[3].toString());
            uvo.setUserName(XaUtil.isEmpty(obj[4]) ? "" : obj[4].toString());
            uvo.setMobile(XaUtil.isEmpty(obj[5]) ? "" : obj[5].toString());
            vo.setUservo(uvo);
            vos.add(vo);
        }
        //执行查询语句
        List<Object[]> obj1 = this.query(sql1.toString(), null, null);
        //将得到的查询结果强转成int类型
        int count = Integer.parseInt(obj1.get(0) + "");
        //调用分页
        Page<VSDCExperienceVo> page = new MyPage<VSDCExperienceVo>(nextPage.intValue(), pageSize.intValue(), vos, count);
        //创建结果集对象xr
        XaResult<Page<VSDCExperienceVo>> xr = new XaResult<Page<VSDCExperienceVo>>();
        //将page放入xr
        xr.setObject(page);
        return xr;
    }

    /**
     * 修改义工经历状态
     */
    @Override
    public XaResult<VSDCExperience> multiOperateState(String modelIds, Integer vSDC_State) throws BusinessException {
        XaResult<VSDCExperience> xr = new XaResult<VSDCExperience>();
        if (vSDC_State == null) {
            vSDC_State = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                VSDCExperience obj = VSDCExperienceRepository.findByIdAndStatusNot(Long.parseLong(id), vSDC_State);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setVSDC_State(vSDC_State);
                    obj = VSDCExperienceRepository.save(obj);

                    if (vSDC_State == 2) {//审核通过,进行积分操作

                        XaResult<ConfigurationTableVo> configResult = configurationTableService.findLastOne();
                        if (configResult == null || configResult.getObject() == null) {
                            xr.error(configResult.getMessage());
                            return xr;
                        }

                        //赚钱记录表新增一条记录(+10)(转盘抽奖任务)
                        double lotteryTaskMoney = configResult.getObject().getIncome_expenses_nurseExperience_coin();
                        Long userId = Long.parseLong(obj.getUserId());
                        XaResult<MakeMoneyTable> makeMoney_LotteryTaskXR = makeMoneyTableService.saveMakeMoneyRecord(userId, JConstant.ConsumeOrMakeMoney.MakeMoney, (int) lotteryTaskMoney, JConstant.IntegralTypeEnum.Nurse_Experience.getIndex());
                    }
                } else {
                    throw new BusinessException(XaConstant.Message.object_not_find);
                }
            }
        }
        return xr;
    }

}
